package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

//前端分页信息 实现类
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    @Override
    public ResponseResult listByName(ChannelDto dto) {
        //        根据名称分页查询
        if(dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
//        使用mybatisplus推荐的lamda表达式的写法
//        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<WmChannel> queryWrapper = Wrappers.lambdaQuery();
        if(StringUtils.isNotBlank( dto.getName())){
//            构建name模糊查询
            queryWrapper.like(WmChannel::getName,dto.getName());
        }
//        构建分页对象
        IPage<WmChannel> page = new Page<>(dto.getPage(),dto.getSize());
//        返回查询结果
        IPage<WmChannel> page1 = this.page(page, queryWrapper);
//        构建分页结果对象
        return new PageResponseResult(dto.getPage(),dto.getSize(),page1.getTotal(),page1.getRecords());
    }
//保存频道
    @Override
    public ResponseResult saveChannel(WmChannel channel) {
        if (StringUtils.isBlank( channel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //        频道名称不能重复
//        新增之前应该根据名称查询
//        如果能查出结果 返回数据已存在
//        如果没有查出结果再新增
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName,channel.getName());
        WmChannel one = this.getOne(queryWrapper);
        if(one!=null){  // 如果能查出结果 返回数据已存在
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }else{
            channel.setCreatedTime(new Date());
            this.save(channel);
        }
        return ResponseResult.okResult();
    }

}
